
import { Request, Response } from "express";
import {createHash} from 'crypto';

export let tokens = {};
let users = {};

export function loginRouter(req: Request, res: Response) {

    if (req.method == "GET") {
        res.render('login');
    } else {
        if (auth(req.body.user_name, req.body.password)) {

            let token = createHash('md5').update(String(Math.random())).digest("hex")
            tokens[token] = req.body.user_name;
            tokens[users[req.body.user_name]] = null;

            users[req.body.user_name] = token;

            res.cookie("token", token, {maxAge: 86400000, httpOnly: true});
            res.send({success: true});
        } else {
            res.send({success: false, msg : "密码错误"});
        }
    }
}

function auth(user_name :string, password:string): boolean {

    return user_name == "cehua" && password == "098765432" ||
    user_name == "zhangyanchi" && password == "123456"
}
